/*
 *  liquidity/cairo-software-actor.vala
 *
 *  Copyright (c) 2008 Patrick Walton <pcwalton@uchicago.edu>
 */

using GLib;
using Clutter;
using CairoLiquidity;
using OpenGL;

namespace Liquidity {
    public class CairoSoftwareActor : CairoActor {
        public override Behaviour get_behavior_for_key_path(string kp, Alpha
                alpha, Timeline timeline)
        {
            switch (kp) {
                case "background_color":
                    /* TODO */
                    return null; 
            }

            return null;
        }

        public Color background_color { get; set; }

        private ImageSurface surface;
        private uint[] texture;

        public override void realize()
        {
            stdout.printf("%d %d\n", (int)get_width(), (int)get_height());
            surface = new ImageSurface(Format.ARGB32, (int)get_width(),
                    (int)get_height());
            Context ctx = new Context(surface);

            ctx.save();
            draw_in_context(ctx);
            ctx.restore();

            texture = new uint[1];
            glGenTextures(1, texture);
            cogl_texture_bind(CGL_TEXTURE_2D, texture[0]);
            cogl_texture_image_2d(CGL_TEXTURE_2D, 4, surface.get_width(),
                    surface.get_height(), CGL_BGRA, CGL_UNSIGNED_BYTE,
                    surface.get_data());
            cogl_texture_set_filters(CGL_TEXTURE_2D, CGL_LINEAR, CGL_LINEAR); 

            set_flags(ActorFlags.REALIZED); 
        }

        public override void paint()
        {
            if (!is_realized())
                realize();

            cogl_push_matrix();
            cogl_enable(CGL_ENABLE_TEXTURE_2D | CGL_ENABLE_BLEND);

            Clutter.Color color;
            color.red = color.green = color.blue = 0xff;
            color.alpha = get_opacity();
            cogl_color(color);

            int x1, y1, x2, y2;
            get_coords(out x1, out y1, out x2, out y2);

            stdout.printf("error %d\n", glGetError());

            /* Render to a quad... */
            cogl_texture_bind(CGL_TEXTURE_2D, texture[0]);
            stdout.printf("error %x\n", glGetError());
            cogl_texture_quad(0, x2 - x1, 0, y2 - y1,
                    (Fixed)UnitFunctions.ZERO, (Fixed)UnitFunctions.ZERO,
                    (Fixed)UnitFunctions.ONE, (Fixed)(UnitFunctions.ONE));

            cogl_pop_matrix();
        }
    }
}

